package io.github.talelin.latticy.service;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * AI图片生成服务
 * 调用豆包API生成图片
 */
@Service
@Slf4j
public class AIImageGenerationService {

    @Value("${ai.image.api-key:49777b3b-9168-4f9c-ad44-cae5559db5e7}")
    private String apiKey;

    @Value("${ai.image.base-url:https://ark.cn-beijing.volces.com/api/v3/images/generations}")
    private String baseUrl;

    private final RestTemplate restTemplate;
    private final ObjectMapper objectMapper;

    public AIImageGenerationService() {
        this.restTemplate = new RestTemplate();
        this.objectMapper = new ObjectMapper();
    }

    /**
     * 生成图片
     * @param prompt 提示词
     * @param model 模型名称
     * @param size 图片尺寸
     * @param guidanceScale 引导强度
     * @param watermark 是否添加水印
     * @return 生成结果
     */
    public AIImageResult generateImage(String prompt, String model, String size, 
                                     Integer guidanceScale, Boolean watermark) {
        try {
            if (prompt == null || prompt.trim().isEmpty()) {
                throw new IllegalArgumentException("提示词不能为空");
            }

            // 构建请求参数
            Map<String, Object> requestData = new HashMap<>();
            requestData.put("model", model != null ? model : "doubao-seedream-3-0-t2i-250415");
            requestData.put("prompt", prompt);
            requestData.put("response_format", "url");
            requestData.put("size", size != null ? size : "1024x1024");
            requestData.put("guidance_scale", guidanceScale != null ? guidanceScale : 3);
            requestData.put("watermark", watermark != null ? watermark : true);

            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);

            // 创建请求实体
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestData, headers);

            log.info("AI图片生成请求参数: {}", requestData);

            // 发送请求
            ResponseEntity<String> response = restTemplate.exchange(
                    baseUrl, 
                    HttpMethod.POST, 
                    requestEntity, 
                    String.class
            );

            log.info("AI图片生成响应: {}", response.getBody());

            // 解析响应
            return parseResponse(response.getBody());

        } catch (Exception e) {
            log.error("AI图片生成失败", e);
            throw new RuntimeException("AI图片生成失败: " + e.getMessage(), e);
        }
    }

    /**
     * 生成商品图片
     * @param productName 商品名称
     * @param productType 商品类型
     * @param style 图片风格
     * @return 生成结果
     */
    public AIImageResult generateProductImage(String productName, String productType, String style) {
        String prompt = String.format("%s，%s，%s，高清产品图片，白色背景，专业摄影，商业级质量", 
                                    style != null ? style : "专业产品摄影", 
                                    productType != null ? productType : "电子产品", 
                                    productName);
        
        return generateImage(prompt, "doubao-seedream-3-0-t2i-250415", "1024x1024", 3, true);
    }

    /**
     * 生成用户头像
     * @param description 头像描述
     * @param style 图片风格
     * @return 生成结果
     */
    public AIImageResult generateAvatar(String description, String style) {
        String prompt = String.format("%s，%s，头像，圆形，简洁设计，适合作为用户头像", 
                                    style != null ? style : "卡通头像", 
                                    description);
        
        return generateImage(prompt, "doubao-seedream-3-0-t2i-250415", "512x512", 3, false);
    }

    /**
     * 生成横幅图片
     * @param title 横幅标题
     * @param theme 主题
     * @return 生成结果
     */
    public AIImageResult generateBanner(String title, String theme) {
        String prompt = String.format("%s风格横幅，%s，横向布局，高清，商业用途", 
                                    theme != null ? theme : "现代商务", 
                                    title);
        
        return generateImage(prompt, "doubao-seedream-3-0-t2i-250415", "1920x1080", 3, true);
    }

    /**
     * 解析API响应
     */
    private AIImageResult parseResponse(String responseBody) {
        try {
            JsonNode rootNode = objectMapper.readTree(responseBody);
            
            if (rootNode.has("data") && rootNode.get("data").isArray() && 
                rootNode.get("data").size() > 0) {
                
                JsonNode dataNode = rootNode.get("data").get(0);
                
                AIImageResult result = new AIImageResult();
                result.setSuccess(true);
                result.setUrl(dataNode.has("url") ? dataNode.get("url").asText() : null);
                result.setRevisedPrompt(dataNode.has("revised_prompt") ? 
                                      dataNode.get("revised_prompt").asText() : null);
                
                return result;
            } else {
                throw new RuntimeException("图片生成失败：响应数据格式错误");
            }
            
        } catch (Exception e) {
            log.error("解析AI图片生成响应失败", e);
            throw new RuntimeException("解析响应失败: " + e.getMessage(), e);
        }
    }

    /**
     * AI图片生成结果
     */
    public static class AIImageResult {
        private boolean success;
        private String url;
        private String revisedPrompt;
        private String errorMessage;

        // Getters and Setters
        public boolean isSuccess() {
            return success;
        }

        public void setSuccess(boolean success) {
            this.success = success;
        }

        public String getUrl() {
            return url;
        }

        public void setUrl(String url) {
            this.url = url;
        }

        public String getRevisedPrompt() {
            return revisedPrompt;
        }

        public void setRevisedPrompt(String revisedPrompt) {
            this.revisedPrompt = revisedPrompt;
        }

        public String getErrorMessage() {
            return errorMessage;
        }

        public void setErrorMessage(String errorMessage) {
            this.errorMessage = errorMessage;
        }
    }
}

